package net.freestu.looker.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;



/**
 * Project  : Test
 * Package  : 
 * File     : CdutIndexTest.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : 2009-9-18
 * Modified : 2009-9-18
 * License  : Apache License 2.0 
 */

/**
 *  
 */
public class CdutIndexTest
{

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException
	{
		URL url = new URL("http://www.cdut.edu.cn/c3.aspx?classid=3");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		String html = fetchHtml(conn.getInputStream());
		Pattern pt = null;
		Matcher mc = null;
		parse(html);
		pt = Pattern.compile("<input type=\"hidden\" name=\"__VIEWSTATE\" value=\"(.*?)\" />");
		mc = pt.matcher(html);
		String vs = null;
		if(mc.find())
			vs = mc.group(1);
		String cookies = conn.getHeaderField("Set-Cookie");
		cookies = cookies.substring(0,cookies.indexOf(';'));
		System.out.println(cookies);
		System.out.println(vs);
		System.out.println("----------------------------------------");
		url = new URL("http://www.cdut.edu.cn/c3.aspx?classid=3");
		conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Cookie", cookies);
		conn.setDoOutput(true);
		PrintWriter writer = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
		writer.println();
		writer.println("__VIEWSTATE="+vs+"&__EVENTTARGET=Linkbutton3&__EVENTARGUMENT=&Top1:keyWord");
		writer.println();
		//writer.println();
		writer.flush();
		html = fetchHtml(conn.getInputStream());
		parse(html);
		
		
	}
	
	public static String fetchHtml(InputStream in) throws IOException
	{
    		BufferedReader r = new BufferedReader(
    							new InputStreamReader(in,"GBK"));
    		StringBuffer s = new StringBuffer();
    		String line = null;
    		while ( (line = r.readLine())!=null )
    		{
    			//去除空白字符 TODO 可以用正则表达式去除 。。。
    			line = line.replaceAll("\t", "");
    			line = line.replaceAll("\r", "");
    			line = line.replaceAll("\n", "");
    			s.append(line);
    		}
    		return s.toString();
	}
	
	public static void parse(String html)
	{
		Pattern pt = Pattern.compile("<td class=\"wzi\" valign=\"top\"><img src=\"PIC/class_content.gif\"><a href=n(.*?).aspx target=_blank>(.*?)</a></td>");
		Matcher mc = pt.matcher(html);
		System.out.println(html);
		while(mc.find()) {
			System.out.println(mc.group(1));
		}
	}

}
